﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GPSTrackingWebsiteManager.ClassManager;
using Telerik.Web.UI;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class ClientsRealTime : ClassManager.SessionManagerPage
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                beginDateSelected.SelectedDate = DateTime.Now.Date;
                endDateSelected.SelectedDate = DateTime.Now.Date;
                
                GridSortExpression expression = new GridSortExpression();
                expression.FieldName = "Name";
                expression.SetSortOrder("Ascending");
                this.ClientsControlGrid.MasterTableView.SortExpressions.AddSortExpression(expression);
            }
        }

        protected void lbClearFilters_Click(object sender, EventArgs e)
        {
            ClientsControlGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in ClientsControlGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            ClientsControlGrid.MasterTableView.Rebind();
        }

        public string getFormatDate(string date)
        {

            string day = date.Substring(0, 2);
            string month = date.Substring(3, 2);
            string year = date.Substring(6, 4);

            return year + '/' + month + '/' + day;
        }

        public bool isDate(string date)
        {
            try
            {
                DateTime.Parse(date);
                return true;
            }
            catch
            {
                return false;
            }
        }

        protected void ClientsControlGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            getInfoGrid();
            resizeGrid();
        }

        protected void resizeGrid(){
            ClientsControlGrid.Height = Unit.Parse((float.Parse(HiddenFieldHeight.Value.ToString()) - 125).ToString());
        }

        protected void btnVPCProcessSearch_Click(object sender, EventArgs e)
        {
            if(getInfoGrid())
                ClientsControlGrid.DataBind();
            resizeGrid();
        }

        protected bool getInfoGrid() {
            SessionManager objSessionManager = getSessionManager();
            int companyID = -1;
            if (objSessionManager != null)
                companyID = objSessionManager.CompanyIDSelectedComboBox;

            try
            {
                if (beginDateSelected.SelectedDate != null)
                {
                    if (!isDate(beginDateSelected.SelectedDate.Value.ToString()))
                    {
                        showWarningMessage("La fecha de inicio seleccionada no es válida para la consulta.");
                        return false;
                    }
                }
                else {
                    showInfoMessage("No se ha seleccionado la fecha de inicio para la consulta.");
                    return false;
                }

                if (endDateSelected.SelectedDate != null)
                {
                    if (!isDate(endDateSelected.SelectedDate.Value.ToString()))
                    {
                        showWarningMessage("La fecha de fin seleccionada no es válida para la consulta.");
                        return false;
                    }
                }
                else {
                    showInfoMessage("No se ha seleccionado la fecha de fin para la consulta.");
                    return false;
                }

                if (beginDateSelected.SelectedDate.Value > endDateSelected.SelectedDate.Value)
                {
                    showWarningMessage("La fecha de inicio no puede ser mayor a la fecha de fin.");
                    return false;
                }

                ClientsControlGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.ClientsControlProvider.GetByDatesByCompanyID(beginDateSelected.SelectedDate.Value, endDateSelected.SelectedDate.Value, companyID);

                return true;
                /*if (ClientsControlGrid.MasterTableView.Items.Count > 10)
                {
                    this.ClientsControlGrid.Height = Unit.Percentage(100);
                }
                else
                {
                    this.ClientsControlGrid.Height = Unit.Parse("300px");
                }*/

            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo obtener la información.");
                return false;
            }
        }
        
        protected SessionManager getSessionManager()
        {
            return (SessionManager)HttpContext.Current.Session["SessionManager"];
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Error", "objWindowsMessageManager.show_Error('" + msg + "','Resumen de Rutas...');", true);
        }

        public void showInfoMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Info", "objWindowsMessageManager.show_Info('" + msg + "','Resumen de Rutas...');", true);
        }

        public void showWarningMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Warning", "objWindowsMessageManager.show_Warning('" + msg + "','Resumen de Rutas...');", true);
        }

        protected void btnVPCProcessExecution_Click(object sender, EventArgs e)
        {
            try
            {
                SessionManager objSessionManager = getSessionManager();
                int companyID = -1;
                if (objSessionManager != null)
                    companyID = objSessionManager.CompanyIDSelectedComboBox;
                GPSTrackingDBV2Custom.Data.DataRepository.ClientsControlProvider.ExecuteProcessByCompanyID(companyID);
                System.Threading.Thread.Sleep(500);
                if(getInfoGrid())
                    ClientsControlGrid.DataBind();
                resizeGrid();
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo ejecutar el proceso correctamente.");
            }
        }

        protected void tbVPCProcessClear_Click(object sender, EventArgs e)
        {
            List<string> usernames = new List<string>();
            List<string> GPSImeis = new List<string>();
            List<string> dates = new List<string>();
            string result = string.Empty;

            if (ClientsControlGrid.SelectedItems.Count > 0)
            {

                foreach (Telerik.Web.UI.GridDataItem selectedItem in ClientsControlGrid.SelectedItems)
                {
                    usernames.Add(selectedItem["Username"].Text);
                    GPSImeis.Add(selectedItem["GPSImei"].Text);
                    dates.Add(getFormatDate(selectedItem["Date"].Text));
                }

                result = GPSTrackingDBV2Custom.Data.DataRepository.ClientsControlProvider.ClearByPrimaryKey(getSessionManager().CompanyIDSelectedComboBox, usernames, GPSImeis, dates);

                if (string.IsNullOrEmpty(result))
                {
                    if(getInfoGrid())
                        ClientsControlGrid.DataBind();
                    resizeGrid();
                }
                else
                {
                    showWarningMessage("No se restablecieron los siguientes números de control: " + result + " porque se encuentra en proceso de ejecución, intente una vez finalizado el proceso.");
                }
            }
            else
            {
                showInfoMessage("Debe seleccionar almenos un registro para poder ejecutar esta acción.");
            }

        }
    }
}